package com.youlu.campus.admin.card.service;

import com.google.common.collect.Lists;
import com.youlu.campus.admin.card.dto.CardOrderSearchDTO;
import com.youlu.campus.entity.card.entity.CardOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : [dengbo]
 * @className : CardOrderService
 * @description : [视频卡订单]
 * @createTime : [2022/12/20 15:42]
 */
@Service
@Slf4j
public class CardOrderService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public Page<CardOrder> list(CardOrderSearchDTO dto) {
        Query query = new Query();
        if (StringUtils.isNotBlank(dto.getThirdGoodsCode())) {
            query.addCriteria(Criteria.where("thirdGoodsCode").is(dto.getThirdGoodsCode()));
        }
        if (StringUtils.isNotBlank(dto.getOrderNo())) {
            query.addCriteria(Criteria.where("orderNo").is(dto.getOrderNo()));
        }
        if (dto.getStatus() != null && dto.getStatus() >= 0) {
            query.addCriteria(Criteria.where("status").is(dto.getStatus()));
        }
        long count = mongoTemplate.count(query, CardOrder.class);
        query.with(Sort.by(Sort.Order.desc("createdTime")));
        PageRequest pageRequest = PageRequest.of(dto.getPage() - 1, dto.getPageSize());
        List<CardOrder> datas = mongoTemplate.find(query.with(pageRequest), CardOrder.class);
        datas.stream().forEach(item -> {
            if (!Lists.newArrayList(3, 4).contains(item.getStatus())) {
                item.setRefundReason(null);
            }
        });
        return PageableExecutionUtils.getPage(datas, pageRequest, () -> count);
    }

}
